package com.apes.hr.transfer.model;

import com.alibaba.fastjson.annotation.JSONField;
import com.apes.framework.api.SpringManager;
import com.apes.framework.jpa.DefaultPersistListener;
import com.apes.framework.jpa.Model;
import com.apes.framework.jpa.comment.Comment;
import com.apes.framework.jpa.generator.ApesGenerator;
import com.apes.framework.util.DateUtil;
import com.apes.hr.base.model.*;
import com.apes.scm.masterdata.enumeration.model.Enumeration;
import com.apes.scm.masterdata.enumeration.repository.EnumerationRepository;
import com.apes.scm.masterdata.frame.model.Branch;
import com.apes.scm.masterdata.party.model.PartyRole;
import com.apestech.framework.util.StringUtil;
import lombok.Getter;
import lombok.Setter;
import org.hibernate.annotations.DynamicInsert;
import org.hibernate.annotations.DynamicUpdate;
import org.hibernate.annotations.SelectBeforeUpdate;
import org.springframework.util.StringUtils;

import javax.persistence.*;
import java.util.*;

/**
 * 功能：离职申请单
 * @author HuJianlin
 * @create 2018-05-05 15:11
 */
@Getter
@Setter
@SelectBeforeUpdate
@DynamicInsert
@DynamicUpdate
@Entity
@EntityListeners(DefaultPersistListener.class)
@Table(name = QuitJobOrder.CONST_TABLE_NAME)
public class QuitJobOrder extends Model {
    public static final String CONST_TABLE_NAME = "hr_Quit_Job_Order";

    @Id
    @Column(name = "id")
    @ApesGenerator(code = CONST_TABLE_NAME, name = "离职申请单号", prefix = "H", padding = 7)
    private String id;   //离职申请单号

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "employee_id", referencedColumnName = "id")
    private Employee employee; //员工

//    @Name
//    @Column(name = "employee_number", length = 200)
//    private PartyRole employeeNumber; //工号

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "party_id", referencedColumnName = "id")
    private PartyRole party; //工号

    @Column(name = "ORIGIN", length = 32)
    private String origin;  //工号

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "work_branch_id", referencedColumnName = "id")
    private Branch workBranch; //工作部门

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "post_id", referencedColumnName = "id")
    private WorkPost post; //岗位

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "job_id", referencedColumnName = "id")
    private Job job; //职位

    @Column(name = "post_describe",length = 120)
    private String postDescribe;//岗位描述

//    @ManyToOne(fetch = FetchType.LAZY)
//    @JoinColumn(name = "person_group", referencedColumnName = "id")
//    private PersonGroup personnelGrouping; //员工分组  人员分组


    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "quit_class_id", referencedColumnName = "id")
    private Enumeration quitClass; //离职类型

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "on_duty_state", referencedColumnName = "id")
    private Enumeration onDutyState; //在职状态(onDutyState)


//    @OneToMany(mappedBy = "employee", cascade = CascadeType.ALL, orphanRemoval = true)
//    private Set<EmployeeEducation> employeeEducations = new HashSet(); //教育背景
//
//    public Set<EmployeeEducation> getEmployeeEducations() {
//        if (employeeEducations == null) return null;
//        for (EmployeeEducation employeeEducation : employeeEducations) {
//            employeeEducation.setEmployee(this.getEmployee());
//        }
//        return employeeEducations;
//    }
//    @Column(name = "employee_group_id",length = 120)
//    private String  personnelGrouping;//员工分组

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "rank_id", referencedColumnName = "id")
    private Rank rank; //职级

    @JSONField(format = DateUtil.SHOW_DATE_FORMAT)
    @Temporal(TemporalType.DATE)
    @Column(name = "entry_date")
    private Date entryDate;  //入职日期

//    @Column(name = "reason", length = 100)
//    private String reason;    // 离职原因
//
//    @ManyToOne(fetch = FetchType.LAZY)
//    @JoinColumn(name = "reason_id", referencedColumnName = "id")
//    private Enumeration reason; // 离职原因(hrQuitJobReason)

    @Column(name = "reasons_id", length = 4000)
    private String reasons;  //离职原因

    public void setReasons(String reasons){
    }

    @Transient
    private Set<Enumeration> reasonSet;

    public Set<Enumeration> getReasonSet() {
        if (isWrite() || isLoad()) {
            reasonSet = getReason(this.reasons);
        }
        return reasonSet;
    }
    public void setReasonSet(Set<Enumeration> reasonSet) {
        this.reasonSet = reasonSet;
        if (!isWrite()) {
            this.reasons = toConvertReason(this.reasonSet);
        }
    }

    @Transient
    private Set<Enumeration> getReason(String source) {
        if (StringUtil.isEmpty(source)) return null;
        Set<Enumeration> persons = new HashSet<>();
        String[] rows = source.split(";");
        for (String person : rows) {
            if (person.contains("|")) {
                persons.add(SpringManager.getBean(EnumerationRepository.class).findOne(StringUtils.split(person, "|")[0]));
            }
        }
        return persons;
    }

    private String toConvertReason(Set<Enumeration> persons) {
        StringBuffer sb = new StringBuffer();
        for (Enumeration enumeration : persons) {
            if (sb.length() > 0) {
                sb.append(";");
            }
            sb.append(enumeration.getId());
            sb.append("|");
            sb.append(enumeration.getDescription());  // 格式 id|description;
        }
        return sb.toString();
    }


    @JSONField(format = DateUtil.SHOW_DATETIME_FORMAT)
    @Temporal(TemporalType.DATE)
    @Column(name = "plan_last_day")
    private Date planLastDay;    // 拟最后工作日

    @JSONField(format = DateUtil.SHOW_DATE_FORMAT)
    @Temporal(TemporalType.DATE)
    @Column(name = "real_last_day")
    private Date realLastDay;    // 实际最后工作日

    @Column(name ="dept_opinion",length = 4000 )
    private String deptOpinion;//直接上级审批意见

    @Column(name = "HQ_inter_opinion",length = 4000)
    private String hqInterOpinion;//直属部门审批意见

    @Column(name = "Hr_opinion",length = 4000)
    private String hrOpinion;    // 人资部审批意见


    @Column(name = "inter_opinion",length = 4000)
    private String interOpinion;    // 面试官审批意见

    @Column(name ="dept_cancel_opinion",length = 4000 )
    private String deptCancelOpinion;//直接上级取消离职审批意见

    @Column(name = "dept_cancel_refuse",nullable = false,columnDefinition = "number(1,0) default 0")
    @Comment("人资是否同意取消离职")
    private boolean deptCancelRefuse = false;    // 直接上级是否同意取消离职

    @Column(name = "HQ_inter_cancel_opinion",length = 4000)
    private String hqInterCancelOpinion;//直属部门取消离职审批意见

    @Column(name = "HQ_inter_cancel_refuse",nullable = false,columnDefinition = "number(1,0) default 0")
    @Comment("人资是否同意取消离职")
    private boolean hqInterCancelRefuse = false;    // 直属部门是否同意取消离职

    @Column(name = "Hr_cancel_opinion",length = 4000)
    private String hrCancelOpinion;    // 人资部取消离职审批意见

    @Column(name = "hr_cancel_refuse",nullable = false,columnDefinition = "number(1,0) default 0")
    @Comment("人资是否同意取消离职")
    private boolean HrCancelRefuse = false;    // 人资是否同意取消离职

//    @Column(name = "dept_interview", length = 100)
//    private String deptInterview;    // 部门第一级主管面谈
//
//    @Column(name = "dept_approve")
//    private boolean deptApprove;    // 部门第一级主管审批
//
//    @Column(name = "dept_Approve_uid")
//    private PartyRole dept1ApproveUID;    // 部门约谈人
//
//    @JSONField(format = DateUtil.SHOW_DATETIME_FORMAT)
//    @Temporal(TemporalType.DATE)
//    @Column(name = "dept_Approve_date")
//    private Date dept1ApproveDate;    // 部门约谈时间
//
//    @Column(name = "HQ_interview", length = 100)
//    private String hqInterview;    // 总部直属部门面谈
//
//    @Column(name = "Hq_approve")
//    private boolean hqApprove;    // 总部直属部门审批
//
//    @Column(name = "hq_Approve_uid")
//    private PartyRole hqApproveUID;    // 总部约谈人
//
//    @JSONField(format = DateUtil.SHOW_DATETIME_FORMAT)
//    @Temporal(TemporalType.DATE)
//    @Column(name = "hq_Approve_date")
//    private Date hqApproveDate;    // 总部约谈时间
//
//    @Column(name = "Hr_interview", length = 100)
//    private String HrInterview;    // 人资部面谈
//
//    @Column(name = "Hr_approve")
//    private boolean HrApprove;    // 人资部审批
//
//    @Column(name = "hr_Approve_uid")
//    private PartyRole hrApproveUID;    // 人资部约谈人
//
//    @JSONField(format = DateUtil.SHOW_DATETIME_FORMAT)
//    @Temporal(TemporalType.DATE)
//    @Column(name = "hr_Approve_date")
//    private Date hrApproveDate;    // 人资部约谈时间


    @JSONField(format = DateUtil.SHOW_DATE_FORMAT)
    @Temporal(TemporalType.DATE)
    @Column(name = "apply_day")
    private Date applyDay;    // 提出离职日期

    @Column(name="quit_job_opinion_date")
    @Comment("直接上级建议最后工作日")
    private Date  quitJobDeptOpinionDate;//直接上级建议最后工作日

    @JSONField(format = DateUtil.SHOW_DATE_FORMAT)
    @Temporal(TemporalType.DATE)
    @Column(name = "approve_last_day")
    private Date approveLastDay;    // 部门建议最后工作日

    @JSONField(format = DateUtil.SHOW_DATE_FORMAT)
    @Temporal(TemporalType.DATE)
    @Column(name = "hr_opinion_day")
    private Date hrOpinionDay;    // 人资建议最后工作日


    @Column(name = "is_blacklist",nullable = false,columnDefinition = "number(1,0) default 0")
    @Comment("人资是否计入黑名单")
    private boolean isBlacklist = false;    // 人资是否计入黑名单

    @Column(name = "secondary_employment", nullable = false, columnDefinition = "number(1,0) default 0")
    @Comment("人资是否可二次聘用")
    private boolean secondaryEmployment = false; //人资是否可二次聘用

    @Column(name = "upper_is_blacklist",columnDefinition = "number(1,0) default 0")
    @Comment("直属上级是否计入黑名单")
    private boolean upperIsBlacklist = false;    // 直属上级 是否计入黑名单

    @Column(name = "upper_secondary_employment", columnDefinition = "number(1,0) default 0")
    @Comment("直属上级是否可二次聘用")
    private boolean upperSecondaryEmployment = false; //直属上级 是否可二次聘用

    @Column(name = "dept_is_blacklist",columnDefinition = "number(1,0) default 0")
    @Comment("管理部门是否计入黑名单")
    private boolean upperDeptIsBlacklist = false;    // 管理部门 是否计入黑名单

    @Column(name = "inter_is_blacklist",columnDefinition = "number(1,0) default 0")
    @Comment("面试官是否计入黑名单")
    private boolean interIsBlacklist = false;    // 面试官是否计入黑名单

    @Column(name = "dept_secondary_employment",  columnDefinition = "number(1,0) default 0")
    @Comment("管理部门是否可二次聘用")
    private boolean upperDeptSecondaryEmployment = false; //管理部门 是否可二次聘用

    @Column(name = "inter_secondary_employment",  columnDefinition = "number(1,0) default 0")
    @Comment("面试官是否可二次聘用")
    private boolean  interSecondaryEmployment = false; //面试官是否可二次聘用


    @Column(name = "work_handover_focus", nullable = true, length = 200)
    @Comment("工作交接重点")
    private String workHandoverFocus; //人资工作交接重点

    @Column(name = "hr_work_handover_focus", nullable = true, length = 200)
    @Comment("工作交接重点")
    private String hrWorkHandoverFocus; //工作交接重点

    @Column(name = "upper_work_handover_focus", nullable = true, length = 200)
    @Comment("上级工作交接重点")
    private String upperWorkHandoverFocus; //上级工作交接重点

    @Column(name = "upper_dept_work_handover_focus", nullable = true, length = 200)
    @Comment("直属部门工作交接重点")
    private String upperDeptWorkHandoverFocus; //直属部门工作交接重点

    @Column(name = "inter_work_handover_focus", nullable = true, length = 200)
    @Comment("面试官工作交接重点")
    private String interWorkHandoverFocus;//面试官工作交接重点
//

//
//    @JSONField(format = DateUtil.SHOW_DATE_FORMAT)
//    @Temporal(TemporalType.DATE)
//    @Column(name = "last_payday")
//    private Date lastPayday; // 最后计薪日
//
//    @Column(name = "confirm_quit_uid")
//    private PartyRole confirmQuitUid;    // 离职确认人
//
//    @JSONField(format = DateUtil.SHOW_DATETIME_FORMAT)
//    @Temporal(TemporalType.DATE)
//    @Column(name = "date_confirm_quit")
//    private Date dateConfirmQuit; // 离职确认日期

    @Column(name = "state", length = 10, nullable = false)
    private String state; //状态：('create', '制单'), ('confirm', '确认')('approve','审核')

    // 重点交接（在何时填写？）（工作交接确认单、资产转移单）

    @Column(name = "interviewer_id", length = 120)
    private String interviewerId; //面试官(保存的是UserId)

    @Column(name = "superior", length = 120)
    private String superior;//直属上级（审批流使用）

    @Column(name = "repeal", length = 1100)
    private String repeal;//终止原因

    @Column(name="last_pay_dy")
    @Comment("最后记薪日")
    private Date lastPayDy;//最后记薪日

    @Column(name = "quit_job_reason",length = 2000)
    @Comment("具体离职原因")
    private String quitJobReason;

    @Column(name = "dismiss", nullable = false, columnDefinition = "number(1,0) default 0")
    @Comment("是否解除劳动合同")
    private boolean dismiss;  //是否解除劳动合同

    @Column(name = "real_Last_Day_Cause", length = 1100)
    private String realLastDayCause;//调整实际最后工作日原因

    @Column(name = "finish",columnDefinition = "number(1,0) default 0")
    @Comment("是否结束OA流程")
    private Boolean finish;
//    @Column(name = "user_List")
//    private List<> userList; //面试官(保存的是UserId)

}
